package com.adui.mgt.performance.service;

import cn.hutool.core.collection.CollUtil;
import com.adui.mgt.performance.common.Result;
import com.adui.mgt.performance.entity.Role;
import com.adui.mgt.performance.entity.User;
import com.adui.mgt.performance.entity.UserRole;
import com.adui.mgt.performance.mapper.UserRoleMapper;
import com.adui.mgt.performance.service.base.impl.BaseServiceImpl;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.adui.mgt.performance.common.CommonUtil.handleObjLog;

@Service
public class UserRoleService extends BaseServiceImpl<UserRoleMapper, UserRole> {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Transactional(rollbackFor = Exception.class)
    public Result saveUserRoleRel(UserRole userRole) {

        // 校验参数
        Set<String> userIds = userRole.getUserIds();
        if (CollUtil.isEmpty(userIds)) {
            return Result.error("userIds不能为空");
        }
        String roleId = userRole.getId();
        if (StringUtils.isBlank(roleId)) {
            return Result.error("role id不能为空");
        }

        // 用户校验
        List<User> users = userService.list(Wrappers.<User>lambdaQuery().in(User::getId, userIds));
        if (CollUtil.isEmpty(users) || !Objects.equals(users.size(), userIds.size())) {
            return Result.error("user信息错误");
        }

        // 组装本次rel data
        List<UserRole> urs = new ArrayList<>();
        userIds.forEach(uid -> {
            UserRole ur = new UserRole();
            ur.setRoleId(roleId);
            ur.setUserId(uid);
            handleObjLog(ur);
        });

        // 历史关系过滤
        List<UserRole> hurs = this.list(Wrappers.<UserRole>lambdaQuery().in(UserRole::getUserId, userIds).eq(UserRole::getRoleId, roleId));
        if (CollUtil.isEmpty(hurs)) {
            Map<String, String> hurMap = hurs.stream().collect(Collectors.toMap(UserRole::getUserId, UserRole::getUserId));
            urs.removeIf(ur -> Objects.nonNull(hurMap.get(ur.getUserId())));
        }

        if (CollUtil.isNotEmpty(urs)) {
            this.saveBatch(urs);
        }

        return Result.ok();
    }
}
